package com.qingjiang.projectschedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingjiang.projectschedule.mapper.UserInfoMapper;
import com.qingjiang.projectschedule.mapper.UserMapper;
import com.qingjiang.projectschedule.pojo.User;
import com.qingjiang.projectschedule.pojo.UserInfo;
import com.qingjiang.projectschedule.service.UserService;
import com.qingjiang.projectschedule.utils.JwtUtil;
import com.qingjiang.projectschedule.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author jx
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-03-13 20:05:11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String userName = user.getUsername().substring(3);
        userLambdaQueryWrapper.eq(User::getUsername, userName);
        User queryUser = userMapper.selectOne(userLambdaQueryWrapper);
        if (queryUser == null) {
            return Result.build(null, 404, "用户名或密码错误", false);
        }
        Integer uid = queryUser.getUid();
        String token = jwtUtil.createToken(uid);
        return Result.ok(token);
    }

    @Override
    public Result login_new(Map map) {
        if (!map.containsKey("iStaffId")) return Result.build(null, 601, "用户不存在", false);
        Long iStaffId = (Long) map.get("iStaffId");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getIstaffid, iStaffId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.build(null, 601, "用户未导入！", false);
        }
        LambdaQueryWrapper<UserInfo> infoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        infoLambdaQueryWrapper.select(UserInfo::getIsAbandon).eq(UserInfo::getIstaffid, iStaffId);
        List<Map<String, Object>> maps = userInfoMapper.selectMaps(infoLambdaQueryWrapper);
        if ((Integer) maps.get(0).get("is_abandon") == 1) {
            return Result.build(null, 601, "用户被禁用！", false);
        }
        String token = jwtUtil.createToken(user.getUid());
        return Result.ok(token);
    }

    @Override
    public Integer insertUser(Integer uid, Long istaffid, String username) {
        User user = new User();
        user.setUsername(username);
        user.setUid(uid);
        user.setIstaffid(istaffid);
        return userMapper.insert(user);
    }


}




